import { getValue, setValue } from './tools';

export default class histroy {
    undoStack: any[] = [];
    redoStack: any[] = [];
    jsonData: any = {};
    constructor() { }
    setState(data: any) {
        this.jsonData = data;
    }
    change(key: string, value: any) {
        const lastChangeObj = this.undoStack[this.undoStack.length - 1]?.key;
        if (lastChangeObj.key === key && lastChangeObj.time < new Date().getTime() - 3000) {
            this.undoStack[this.undoStack.length - 1].new = value;
            this.redoStack = [];
            return;
        }
        const old = getValue(this.jsonData, key);
        setValue(this.jsonData, key, value);
        this.undoStack.push({ key, old, new: value, time: new Date().getTime() });
        this.redoStack = [];
    }
    redo() {
        const redoObj = this.redoStack.pop();
        setValue(this.jsonData, redoObj.key, redoObj.new);
        this.undoStack.push(redoObj);
    }
    undo() {
        const undoObj = this.undoStack.pop();
        setValue(this.jsonData, undoObj.key, undoObj.old);
        this.redoStack.push(undoObj);
    }
}
